//
//  HJLocationManager.m
//  project
//
//  Created by hu on 2019/3/30.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJLocationManager.h"
#import <CoreLocation/CoreLocation.h>
//地理编码头文件
#import <AddressBook/AddressBook.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface HJLocationManager ()<AMapLocationManagerDelegate,AMapSearchDelegate>
@property (nonatomic, strong) CLGeocoder *geoC;
@property (nonatomic,strong,nonnull) AMapLocationManager * locationManager;
@property (strong,nonatomic) AMapSearchAPI *ASearch;
@end
@implementation HJLocationManager

+(instancetype)manager {
    static HJLocationManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc]init];
    });
    return manager;
}
-(instancetype)init {
    if (self == [super init]) {
        [self startLocation];
    }
    return self;
}

-(void)startLocation {
    if (self.locationManager==nil) {
        self.locationManager = [[AMapLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [self.locationManager setPausesLocationUpdatesAutomatically:NO];
        [self.locationManager setAllowsBackgroundLocationUpdates:NO];
        [self.locationManager setLocatingWithReGeocode:YES];
        [self.locationManager startUpdatingLocation];
       
        //初始化搜索类
        self.ASearch = [[AMapSearchAPI alloc] init];
        self.ASearch.delegate = self;
    }else {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"" message:@"请开启位置服务" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                [[UIApplication sharedApplication] openURL:settingURL options:nil completionHandler:nil];
            }
        }];
        UIAlertAction * cancleAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action];
        [alert addAction:cancleAction];
        [[UIViewController currentViewController] presentViewController:alert animated:YES completion:nil];
    }
}


#pragma AMapLocationManagerDelegate 定位成功
-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    [mUserDefaults setValue:[NSString stringWithFormat:@"%f",location.coordinate.latitude] forKey:@"lat"];
    [mUserDefaults setValue:[NSString stringWithFormat:@"%f",location.coordinate.longitude] forKey:@"lng"];
    [mUserDefaults synchronize];
    if (self.locationManagerBlock) {
        self.locationManagerBlock(location);
    }
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    regeo.requireExtension = YES;
    [self.ASearch AMapReGoecodeSearch:regeo];
    //停止定位
    [self.locationManager stopUpdatingLocation];
}

-(void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    [[UIViewController currentViewController] showErrorHUDWithError:@"定位失败，请重新定位"];
}
-(void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager {
     [locationManager requestWhenInUseAuthorization];
}

-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    if (response.regeocode !=nil) {
        LocationModel * model = [[LocationModel alloc]init];
        model.lat = [mUserDefaults objectForKey:@"lat"];
        model.lng = [mUserDefaults objectForKey:@"lng"];
        model.addreess = response.regeocode.formattedAddress;
        model.city = response.regeocode.addressComponent.city;
        model.citycode= response.regeocode.addressComponent.citycode;
        model.SubLocality = response.regeocode.addressComponent.district;
        model.street = response.regeocode.addressComponent.township;
        model.neighborhood = response.regeocode.addressComponent.neighborhood;
        model.province= response.regeocode.addressComponent.province;
        if (response.regeocode.pois.count>0) {
            AMapPOI * poi = response.regeocode.pois[0];
            model.dAddressLines = poi.name;
        }
        //停止定位
        [self.locationManager stopUpdatingLocation];
        if (self.locationBlock) {
            self.locationBlock(model);
        }
    }else {
        NSLog(@"不知道");
    }
}
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//    CLLocation *location = [locations lastObject];
//    NSDate *eventDate = location.timestamp;
//    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
//    if (fabs(howRecent) < 15.0) {
//        NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
//        [self getAddressByLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
//    }
//
//}
//- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//    NSLog(@"定位失败%@",error);
//}

//-(void)getAddressByLatitude:(CLLocationDegrees)lat longitude:(CLLocationDegrees)lng {
//    CLLocation *location= [[CLLocation alloc]initWithLatitude:lat longitude:lng];
//
//    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
//        CLPlacemark *placemark = [placemarks firstObject];
//        CLLocation *location = placemark.location;//位置
////        CLRegion *region = placemark.region;//区域
//        LocationModel * model = [[LocationModel alloc]init];
//        model.lat = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
//        model.lng = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
//        model.city = [NSString stringWithFormat:@"%@",placemark.addressDictionary[@"City"]];
//        model.country = [NSString stringWithFormat:@"%@",placemark.addressDictionary[@"Country"]];
//        model.FormattedAddressLines = [NSArray arrayWithArray:placemark.addressDictionary[@"FormattedAddressLines"]];
//        model.Thoroughfare = [NSString stringWithFormat:@"%@",placemark.addressDictionary[@"Thoroughfare"]];
//        model.street = [NSString stringWithFormat:@"%@",placemark.addressDictionary[@"Street"]];
//        model.SubLocality = [NSString stringWithFormat:@"%@",placemark.addressDictionary[@"SubLocality"]];
//        if (self.locationBlock) {
//            self.locationBlock(model);
//        }
//    }];
//}



@end


@implementation LocationModel

-(instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    return [self yy_modelInitWithCoder:aDecoder];
    //    self.country = [aDecoder decodeObjectForKey:@"Country"];
    //    self.city = [aDecoder decodeObjectForKey:@"City"];
    //    self.SubLocality = [aDecoder decodeObjectForKey:@"SubLocality"];
    //    self.street = [aDecoder decodeObjectForKey:@"Street"];
    //    self.Thoroughfare = [aDecoder decodeObjectForKey:@"Thoroughfare"];
    //    self.FormattedAddressLines = [aDecoder decodeObjectForKey:@"FormattedAddressLines"];
    //    self.lat = [aDecoder decodeObjectForKey:@"lat"];
    //    self.lng = [aDecoder decodeObjectForKey:@"lng"];
}

-(void)encodeWithCoder:(NSCoder *)aCoder {
    [self yy_modelEncodeWithCoder:aCoder];
//    [aCoder encodeObject:self.country forKey:@"Country"];
//    [aCoder encodeObject:self.city forKey:@"City"];
//    [aCoder encodeObject:self.SubLocality forKey:@"SubLocality"];
//    [aCoder encodeObject:self.street forKey:@"Street"];
//    [aCoder encodeObject:self.Thoroughfare forKey:@"Thoroughfare"];
//    [aCoder encodeObject:self.FormattedAddressLines forKey:@"FormattedAddressLines"];
//    [aCoder encodeObject:self.lat forKey:@"lat"];
//    [aCoder encodeObject:self.lng forKey:@"lng"];
}

- (id)copyWithZone:(NSZone *)zone {
    return [self yy_modelCopy];
}

@end
